import React, { useState, useEffect } from 'react';
import FormItem from '../../../../components/FormItem';
import { Form, Input, Button, Row, Col, Select, message, TimePicker } from 'antd';
import useAppProductEventData from 'src/hook/useAppProductEventData';
import services from '../../../../services/api';
import ReceiveUser from '../../components/ReceiveUser';
import moment from 'moment';

const layout = {
  labelCol: {
    span: 3,
  },
  wrapperCol: {
    span: 21,
  },
};

function DataReportAdd(props) {
  const { record = {}, actionType, closeModal, form } = props;
  const [riskTypes, setRiskTypes] = useState([]);
  // const [reportItems, setReportItems] = useState(props.data_report_report_item || []);

  // const emailReg = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;

  useEffect(() => {
    getRiskTypeList();
  }, []);

  const {
    report_name,
    app_id,
    product_id,
    event_id,
    remark,
    risk_type_id = -1,
    send_period_type = 3,
    send_time,
    send_date,
    users,
    // status,
    // report_items,
    // received_emails,
  } = record;

  const { items } = useAppProductEventData({
    ...props,
    app_id,
    event_id,
    product_id,
    layout,
    disabled: actionType !== 'add',
    form,
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    form.validateFields((err, values) => {
      if (!err) {
        // const recerived_emails =
        //   values.received_emails && values.received_emails.replace(/\n/g, ',').replace(/\s/g, '');
        // if (recerived_emails.length === 0) {
        //   message.warning('请输入正确的发送邮件');
        //   return;
        // }
        if (values.users.some((item) => !item.phone && !item.wx_work && !item.email)) {
          return message.warning('请至少填写一种接收方式');
        }
        const { users: tempUsers } = values;
        const users = tempUsers.filter(Boolean).map((item) => {
          const { key, label } = item.user_id;
          item['name'] = Array.isArray(label) ? label[0] : label;
          item['user_id'] = key;
          return item;
        });
        const params = {
          send_date: '',
          ...values,
          users,
          send_time: values.send_time ? values.send_time.format('HH:mm') : '',
          // received_emails: recerived_emails.length > 0 && recerived_emails.split(','),
        };
        if (props.actionType === 'update') {
          params.id = props.record.id;
          params.status = values.status ? 1 : 2;
        }
        services.dataReport[props.actionType](params).then((data) => {
          if (data.code === 0) {
            message.success(data.msg);
            closeModal && closeModal();
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  // 获取风险类型列表
  function getRiskTypeList() {
    services.policy.riskTypeList().then((res) => {
      if (res.code === 0) {
        setRiskTypes([
          {
            id: -1,
            name: '所有风险',
          },
          ...res.data,
        ]);
      }
    });
  }

  const formItems = [
    {
      label: {
        label: '报告名称',
        ...layout,
      },
      name: 'name',
      options: {
        initialValue: report_name,
        rules: [
          { required: true, message: '请输入名称' },
          { max: 128, message: '最长128个字符' },
          { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
        ],
      },
      component: <Input placeholder='报告名称' />,
    },
    {
      label: {
        label: '报告说明',
        ...layout,
      },
      name: 'remark',
      options: {
        initialValue: remark,
        rules: [{ max: 256, message: '最长256个字符' }],
      },
      component: <Input.TextArea placeholder='请输入报告说明' />,
    },
    ...items,
    {
      label: {
        label: '风险类型',
        ...layout,
      },
      name: 'risk_type_id',
      options: {
        initialValue: risk_type_id,
      },
      component: (
        <Select>
          {riskTypes.map((it) => {
            return (
              <Select.Option value={it.id} key={it.id}>
                {it.name}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
  ];
  const formItems_level3 = [
    {
      name: 'send_period_type',
      options: {
        initialValue: send_period_type,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select>
          {props.data_report_send_period_type.map((it) => {
            return (
              <Select.Option value={it.key} key={it.key}>
                {it.value}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
    form.getFieldValue('send_period_type') !== 3 && {
      name: 'send_date',
      options: {
        initialValue: send_date && Number(send_date),
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select>
          {(form.getFieldValue('send_period_type') === 4 ? props.data_report_week : props.data_report_month_date).map(
            (it) => {
              return (
                <Select.Option value={it.key} key={it.key}>
                  {it.value}
                </Select.Option>
              );
            }
          )}
        </Select>
      ),
    },
    {
      name: 'send_time',
      options: {
        initialValue: send_time ? moment(send_time, 'HH:mm') : '',
        rules: [{ required: true, message: '请选择' }],
      },
      component: <TimePicker style={{ width: '100%' }} format={'HH:mm'} />,
    },
  ].filter(Boolean);
  // const formItems4 = [
  //   {
  //     label: {
  //       label: '发送邮件',
  //       ...layout,
  //     },
  //     name: 'received_emails',
  //     options: {
  //       initialValue: received_emails instanceof Array ? received_emails.join('\n') : '',
  //       rules: [
  //         { required: true, message: '请输入' },
  //         {
  //           validator: (rule, value, callback) => {
  //             if (value) {
  //               const val = value
  //                 .replace(/\n/g, ',')
  //                 .replace(/\s/g, '')
  //                 .split(',');
  //               const isValMatchEmailReg = val.every((o) => o && emailReg.test(o));
  //               !isValMatchEmailReg ? callback('无效的邮箱地址') : callback();
  //             } else {
  //               callback();
  //             }
  //           },
  //         },
  //       ],
  //     },
  //     component: (
  //       <Input.TextArea
  //         placeholder='每行请输入一个邮箱地址,输入完成后回车换行，&#10;实例:&#10;ABC@qq.com&#10;BCD@gmail.com'
  //         style={{ height: '90px' }}
  //       />
  //     ),
  //   },
  //   props.actionType === 'update'
  //     ? {
  //         label: {
  //           label: '状态',
  //           ...layout,
  //         },
  //         name: 'status',
  //         options: {
  //           valuePropName: 'checked',
  //           initialValue: status === 1 ? true : false,
  //           rules: [{ required: true, message: '请选择' }],
  //         },
  //         component: <Switch />,
  //       }
  //     : false,
  // ].filter(Boolean);

  return (
    <div className='tantuer-form'>
      <Form onSubmit={() => false} className='login-form'>
        <div className='tantuer-field-area'>
          <Row type='flex'>
            {formItems.map((item) => {
              return (
                <Col span={24} key={item.name}>
                  <FormItem {...props} form={form} item={item} />
                </Col>
              );
            })}
          </Row>
          <Row type='flex'>
            <Col span={3} className='ant-form-item-label'>
              <label className='ant-form-item-required'>接收时间</label>
            </Col>
            <Col span={21}>
              <Row type='flex' gutter={10}>
                {formItems_level3.map((item) => {
                  return (
                    <Col span={form.getFieldValue('send_period_type') === 1 ? 12 : 8} key={item.name}>
                      <FormItem {...props} form={form} item={item} colNum={2} />
                    </Col>
                  );
                })}
              </Row>
            </Col>
          </Row>
          {/* <Row type='flex'>
            {formItems4.map((item) => {
              return (
                <Col span={24} key={item.name}>
                  <FormItem form={form} item={item} colNum={2} />
                </Col>
              );
            })}
          </Row> */}
          <Row type='flex'>
            <Col span={3} className='ant-form-item-label'>
              <label className='ant-form-item-required'>接收人</label>
            </Col>
            <Col span={21}>
              <ReceiveUser {...props} value={users} />
            </Col>
          </Row>
        </div>
        {props.actionType !== 'detail' && (
          <div className='form-btn'>
            <Button type='primary' autoFocus={true} onClick={handleSubmit} className='login-form-button'>
              确定
            </Button>
            <Button className='login-form-button' onClick={() => closeModal(true)}>
              取消
            </Button>
          </div>
        )}
      </Form>
    </div>
  );
}
export default Form.create()(DataReportAdd);
